package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Product;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class ViewSearchServlet extends HttpServlet {
    private static final String SEARCH_PRODUCTS = "/WEB-INF/jsp/catalog/SearchProducts.jsp";
    private String keyword;
    private Account account;
    private LogService logService;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        keyword = request.getParameter("keyword");
        CatalogService service = new CatalogService();
        List<Product> productLists = service.searchProductList(keyword);

        HttpSession session = request.getSession();
        session.setAttribute("productLists",productLists);
        account = (Account)session.getAttribute("account");
        if (account != null){
            logService = new LogService();
            logService.insertLog("Search Product","Keyword:"+keyword, account.getUsername());
        } else {
            logService = new LogService();
            logService.insertLog("Search Product","Keyword:"+keyword, "null");
        }
        request.getRequestDispatcher(SEARCH_PRODUCTS).forward(request,response);
    }
}
